package com.sgb.member.view_model;


import android.text.TextUtils;
import android.view.View;

import com.sgb.member.MemberConfig;
import com.sgb.member.PickCateType;
import com.sgb.member.di.repository.MemberRepertory;
import com.sgb.member.entity.ListMResponse;
import com.sgb.member.entity.MemberBiddingEntity;
import com.sgb.member.entity.MemberBiddingPreEntity;
import com.sgb.member.entity.MemberTenderBean;
import com.sgb.member.entity.MemberTenderListEntity;
import com.sgb.member.ui.fragment.BusinessTenderFragment;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.api.APIManager;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.selection.CommonPopEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;

public class BusinessTenderModel extends BaseViewModel {

    private final BusinessTenderFragment fragment;
    private final MemberRepertory mRepertory;
    private int current;

    private final CommonPopEntity mAll;

    public BusinessTenderModel(BusinessTenderFragment fragment, MemberRepertory repertory) {
        this.fragment = fragment;
        this.mRepertory = repertory;

        mAll = new CommonPopEntity();
        mAll.setNo("");
        mAll.setTypeName("全部");
    }

    public void showOrHideDialog(boolean aBoolean) {
        if (aBoolean) {
            if (!DialogHelper.isShowing()) {
                DialogHelper.showProgressDialog(fragment.getActivity(), "数据获取中...");
            }
        } else {
            DialogHelper.dismissProgressDialog();
            fragment.closeRecyclerRefreshing();
        }
    }

    public void tenderBidderList(int mCurPos, boolean isLoadMore, String companyName, String mNo1,
                                 String mNo2, String mNo3, String mNo4,
                                 String mNo5, String mNo51, String mNo6, String mNo7,
                                 String mNo8, String mNo9, String mNoSort,String level) {
        int currentPage = isLoadMore ? current + 1 : 1;
        showOrHideDialog(true);
        Map<String, Object> map = new HashMap<>();
        map.put("page", currentPage);
        map.put("current", currentPage);
        map.put("limit", 10);
        map.put("keyword", companyName);
        map.put("type", mNo1); // 招标类型：1、机械设备租赁；2、劳务；3、商品材料；4、工程分包
        map.put("goodsType", mNo2); // 招标类型清单分类
        map.put("state", mNo3); // 招标状态
        map.put("verticalType", mNo4); // 报名方式：1、资格预审；2、资格后审；3、报价即报名
        map.put("applyStartTime", mNo5); // 报名开始时间
        map.put("price", mNo6);  // 概算金额
        map.put("province", mNo8);
        map.put("city", mNo9);
        map.put("sortMethod", mNoSort); // 排序方式 1.综合排序; 2.投标开始时间; 3.投标截止时间; 4.概述金额,5 报名开始时间，6 报名截止时间， 7发布时间
        map.put("areacode", mNo8);
        map.put("level", level);
        switch (mCurPos) {
            case 0: // 全部
                map.put("time", mNo51); // 报名结束时间类型
                mRepertory.getApi().tenderAll(map).enqueue(new ICallBack<BaseEntity<ListMResponse<List<MemberTenderBean>>>>() {
                    @Override
                    public void onSuccess(BaseEntity<ListMResponse<List<MemberTenderBean>>> data) {
                        current = data.getData().getCurrent();
                        int total = data.getData().getPages();
                        fragment.refreshRecycler(data.getData().getList(), isLoadMore, current >= total);
                    }

                    @Override
                    public void onFailure(Call<BaseEntity<ListMResponse<List<MemberTenderBean>>>> call, Throwable t) {
                        super.onFailure(call, t);
                        if (!isLoadMore) {
                            fragment.showEmpty();
                        }
                    }

                    @Override
                    public void onFinally() {
                        showOrHideDialog(false);
                    }
                });
                break;
            case 1: // 招标公告
                map.put("time", mNo51); // 报名结束时间类型
                mRepertory.getApi().tenderBidderList(map).enqueue(new ICallBack<BaseEntity<ListMResponse<List<MemberTenderListEntity>>>>() {
                    @Override
                    public void onSuccess(BaseEntity<ListMResponse<List<MemberTenderListEntity>>> data) {
                        current = data.getData().getCurrent();
                        int total = data.getData().getPages();
                        fragment.refreshRecycler(data.getData().getList(), isLoadMore, current >= total);
                    }

                    @Override
                    public void onFailure(Call<BaseEntity<ListMResponse<List<MemberTenderListEntity>>>> call, Throwable t) {
                        super.onFailure(call, t);
                        if (!isLoadMore) {
                            fragment.showEmpty();
                        }
                    }

                    @Override
                    public void onFinally() {
                        showOrHideDialog(false);
                    }
                });
                break;
            case 2: // 直接竞价
                map.put("time", mNo7); // 发布时间
                mRepertory.getApi().tenderBidList(map).enqueue(new ICallBack<BaseEntity<ListMResponse<List<MemberBiddingEntity>>>>() {
                    @Override
                    public void onSuccess(BaseEntity<ListMResponse<List<MemberBiddingEntity>>> data) {
                        current = data.getData().getCurrent();
                        int total = data.getData().getPages();
                        fragment.refreshRecycler(data.getData().getList(), isLoadMore, current >= total);
                    }

                    @Override
                    public void onFailure(Call<BaseEntity<ListMResponse<List<MemberBiddingEntity>>>> call, Throwable t) {
                        super.onFailure(call, t);
                        if (!isLoadMore) {
                            fragment.showEmpty();
                        }
                    }

                    @Override
                    public void onFinally() {
                        showOrHideDialog(false);
                    }
                });
                break;
            case 3: // 招标预告
                map.put("time", mNo51); // 报名结束时间类型
                mRepertory.getApi().tenderPreNoticeList(map).enqueue(new ICallBack<BaseEntity<ListMResponse<List<MemberBiddingPreEntity>>>>() {
                    @Override
                    public void onSuccess(BaseEntity<ListMResponse<List<MemberBiddingPreEntity>>> data) {
                        current = data.getData().getCurrent();
                        int total = data.getData().getPages();
                        fragment.refreshRecycler(data.getData().getList(), isLoadMore, current >= total);
                    }

                    @Override
                    public void onFailure(Call<BaseEntity<ListMResponse<List<MemberBiddingPreEntity>>>> call, Throwable t) {
                        super.onFailure(call, t);
                        if (!isLoadMore) {
                            fragment.showEmpty();
                        }
                    }

                    @Override
                    public void onFinally() {
                        super.onFinally();
                        showOrHideDialog(false);
                    }
                });
                break;
        }
    }

    public void loadTenderType(int curIndex, int type, String category, boolean isShowLeftDialog) {
        showOrHideDialog(true);
        Call<BaseEntity<List<CommonPopEntity>>> call = null;
        Map<String, Object> map = new HashMap<>();
        switch (type) {
            case PickCateType.TYPE_1: // 招标类型
                if (curIndex == 3) {
                    call = mRepertory.getApi().biddingTypeList(); //竞价类型
                } else {
                    call = mRepertory.getApi().tenderNewTypeList();
                }
                break;
            case PickCateType.TYPE_2:
                map.put("type", category);
                call = mRepertory.getApi().getTenderGoodsCategoryAllList(map);
                break;
            case PickCateType.TYPE_3:  // 招标状态
                map.put("areacode", mRepertory.getAreaCode());
                call = mRepertory.getApi().getProjectStatus(map);
                break;
            case PickCateType.TYPE_4: // 招标方式
                call = mRepertory.getApi().getTenderSortSelect();
                break;
            case PickCateType.TYPE_5: // 报名开始时间列表
                // String[] stringTime = new String[]{"全部", "今天&1", "3天内&3", "5天内&5", "10天内&10", "30天内&30", "30天以上&31"};
                List<CommonPopEntity> list = new ArrayList<>();
                list.add(mAll);
                list.add(new CommonPopEntity("1", "今天"));
                list.add(new CommonPopEntity("3", "3天内"));
                list.add(new CommonPopEntity("5", "5天内"));
                list.add(new CommonPopEntity("10", "10天内"));
                list.add(new CommonPopEntity("30", "30天内"));
                list.add(new CommonPopEntity("31", "30天以上"));
                if (isShowLeftDialog) {
                    fragment.showLeftDialog(type, list);
                } else {
                    fragment.setChooseItemData(type, list);
                }
                return;
            case PickCateType.TYPE_6: // 招标概算金额
                call = mRepertory.getApi().getProjectMoney();
                break;
            case PickCateType.TYPE_51: // 报名截至时间
            case PickCateType.TYPE_7: // 发布时间
                call = mRepertory.getApi().getPickTimes();
                break;
        }
        if (call == null) {
            showOrHideDialog(false);
            return;
        }
        call.enqueue(new ICallBack<BaseEntity<List<CommonPopEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CommonPopEntity>> data) {
                if (data.getData() != null && data.getData() != null && data.getData().size() > 0) {
                    switch (type) {
                        case PickCateType.TYPE_1: // 招标类型
                            data.getData().set(0, new CommonPopEntity("", "全部"));
                            break;
                        case PickCateType.TYPE_2:
                            break;
                        case PickCateType.TYPE_3:  // 招标状态
                            List<CommonPopEntity> list = new ArrayList<>();
                            for (CommonPopEntity datum : data.getData()) {
                                if (!"6".equals(datum.getNo())) {
                                    list.add(datum);
                                }
                            }
                            data.getData().clear();
                            data.getData().addAll(list);
                            break;
                        case PickCateType.TYPE_4: // 招标方式
                            break;
                        case PickCateType.TYPE_6: // 招标概算金额
                            break;
                    }
                    if (isShowLeftDialog) {
                        fragment.showLeftDialog(type, data.getData());
                    } else {
                        fragment.setChooseItemData(type, data.getData());
                    }
                } else {
                    if (isShowLeftDialog) {
                        fragment.showLeftDialog(type, new ArrayList<>());
                    } else {
                        fragment.setChooseItemData(type, new ArrayList<>());
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<CommonPopEntity>>> call, Throwable t) {
                super.onFailure(call, t);
                if (isShowLeftDialog) {
                    fragment.showLeftDialog(type, new ArrayList<>());
                } else {
                    fragment.setChooseItemData(type, new ArrayList<>());
                }
            }
        });
    }

    /**
     * 获取省市区地址
     */
    public void getAddressModel(int type) {
        showOrHideDialog(true);
        mRepertory.getApi().getAddressEntityCityList().enqueue(new ICallBack<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
            @Override
            public void onSuccess(BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>> data) {
                showOrHideDialog(false);
                if (data != null && data.getData() != null && data.getData().size() > 0) {
                    List<CommonPopEntity> entities = new ArrayList<>();
                    for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> datum : data.getData()) {
                        entities.add(new CommonPopEntity(datum.getNo(), datum.getSimpleName()));
                    }
                    entities.add(0, mAll);
                    fragment.setChooseItemData(type, entities);
                    fragment.setAddressData(data.getData());
                }
            }
        });
    }

    public void getAddressCityData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData, String no, int type, boolean isShowLeftDialog) {
        for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> scrDatum : scrData) {
            if (scrDatum.getId().equals(no)) {
                List<AddressEntity<List<AddressEntity>>> children = scrDatum.getChildren();
                if (children != null && children.size() > 0) {
                    List<CommonPopEntity> entities = new ArrayList<>();
                    for (AddressEntity<List<AddressEntity>> child : children) {
                        entities.add(new CommonPopEntity(child.getNo(), child.getSimpleName()));
                    }
                    entities.add(0, mAll);
                    if (isShowLeftDialog) {
                        fragment.showLeftDialog(type, entities);
                    } else {
                        fragment.setChooseItemData(type, entities);
                    }
                }
            }
        }
    }

    public void tenderItemClick(MemberTenderBean memberTenderBean) {
        if (memberTenderBean.getBusinessType() == 2) { //1.招标； 2.竞价
            getUrlSetting("competitivePurchase", "?id=" + memberTenderBean.getId());
        } else if (memberTenderBean.getBusinessType() == 1) {
            if (memberTenderBean.getState() == 8) {
                MemberConfig.getInstance().startPickNoticeDetail(fragment.getActivity(), memberTenderBean.getComNo());
            } else {
                MemberConfig.getInstance().startTenderDetails(fragment.getActivity(), memberTenderBean.getId(), 0);
            }
        } else if (memberTenderBean.getBusinessType() == 3) {
            boolean saveBooleanData = SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
            String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
            String longitude = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "");
            String latitude = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "");
            if (TextUtils.isEmpty(longitude)) {
                longitude = "0";
            }
            if (TextUtils.isEmpty(latitude)) {
                latitude = "0";
            }
            String endUrl = "?id=" + memberTenderBean.getId() + "&lng=" + longitude + "&lat=" + latitude + "&type=" + memberTenderBean.getModuleType()+"&isDpprove"+saveBooleanData +"&companyNo"+companyNo;
            getUrlSetting("engineeringProject", endUrl);
        }
    }

    public void getUrlSetting(String param, String endUrl) {
        showOrHideDialog(true);
        mRepertory.getApi().getUrlSetting(param).enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                if (data == null || data.getState() == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    String url = data.getData().getUrl() + endUrl;
                    MemberConfig.getInstance().startWebViewX5(fragment.getContext(), url);
                } else {
                    MToast.showToast(fragment.getActivity(), data.getMsg());
                }
            }
        });
    }

    public void getUrlSetting(String param, String endUrl, String id) {
        showOrHideDialog(true);
        mRepertory.getApi().getUrlSetting(param).enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                String url = data.getData().getUrl() + "?id=" + id;
                String lng = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "");
                String lat = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "");
                url = url + "&lng=" + lng + "&lat=" + lat;
                MLog.d("api", "H5跳转链接  " + url);
                MemberConfig.getInstance().startWebViewX5(fragment.getActivity(), url, id);
            }

            @Override
            public void onFailureWithEntity(BaseEntity entity) {
                MToast.showToast(fragment.getActivity(), entity.getMsg());
            }
        });
    }

    public void getSortData(int curIndex) {
        Call<BaseEntity<List<CommonPopEntity>>> call = null;
        switch (curIndex) {
            case 0:
                // 全部
                break;
            case 1:
                // 会员招采经营_招标预告
                call = mRepertory.getApi().getTenderNoticeSortSelect();
                break;
            case 2:
                // 会员招采经营_竞价采购
                call = mRepertory.getApi().getBidSortSelect();
                break;
            case 3:
                // 会员招采经营_招标预告
                call = mRepertory.getApi().getTenderPreNoticeSortSelect();
                break;
        }
        if (call == null) {
            return;
        }
        showOrHideDialog(true);
        call.enqueue(new ICallBack<BaseEntity<List<CommonPopEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CommonPopEntity>> data) {
                if (data.getData() != null && data.getData().size() > 0) {
                    fragment.updateSortInfo(data.getData());
                }
            }
        });
    }

    //会员级别
    public void getMemberLevelData() {
        mRepertory.getApi().getMemberLevelList().enqueue(new ICallBack<BaseEntity<List<CommonPopEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CommonPopEntity>> data) {
                if (data.getData() != null && data.getData() != null && data.getData().size() > 0) {
                    fragment.setMemberLevelData(data.getData());
                } else {
                    fragment.setMemberLevelData(new ArrayList<>());
                }
            }
        });
    }

}
